package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.Share_Adapter;
import com.example.xianji.adapter.TiWen_Adapter;
import com.example.xianji.BGARefresh.BGANormalRefreshViewHolder;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.TiWen;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.SharesUtil;

import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.X5WebView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.sina.weibo.sdk.api.BaseMediaObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.open.t.Weibo;
/*import com.tencent.mm.sdk.openapi.SendMessageToWX;
 import com.tencent.mm.sdk.openapi.WXMediaMessage;
 import com.tencent.mm.sdk.openapi.WXWebpageObject;*/
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 需求详情页面
 *
 * @author me
 */
public class Main_XuQiu_DetailsActivity extends Activity implements
        OnClickListener, BGARefreshLayoutDelegate, IWeiboHandler.Response {
    private Button shenqing_duijie, tiwen_button;
    private ImageView xuqiu_details_iamge_collection, xuqiu_detail_share,
            xuqiu_detail_load;
    private RelativeLayout xuqiu_detail_back;
    //    private SharedPreferences sp;
//    private Editor ed;
    private TextView textView_xuqiu_detail_title, xuqiu_details_bianhao,
            xuqiu_details_place, fabu, yusuan;
    private X5WebView xuqiu_fuwu_details_webview;
    private String id;
    private BGARefreshLayout xuqiu_details_PullToRefreshLayout_two;
    // private MyListview xuqiu_mylistview;
    private ArrayList<TiWen> tiwen_list = new ArrayList<TiWen>();
    private TiWen_Adapter mTiWen_Adapter;
    private LinearLayout layout2;
    private GridView province_gridview;
    private Share_Adapter mShare_Adapter;
    //private ArrayList<Share> share_list = new ArrayList<Share>();
    private PopupWindow show_popupWindow;

    private SsoHandler mSsoHandler;
    private IWeiboShareAPI mWeiboShareAPI = null;
    private Oauth2AccessToken mAccessToken;

    private boolean isInstalledWeibo;
    private int supportApiLevel;
    private String xuqiu_share_url;
    private Weibo mWeibo;
    /**
     * 腾讯微博
     */
    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            initOpenidAndToken(values);
            mWeibo = new Weibo(Main_XuQiu_DetailsActivity.this, XJApplication
                    .getTencent().getQQToken());
            if (ready(Main_XuQiu_DetailsActivity.this)) {
                String content = textView_xuqiu_detail_title.getText()
                        .toString();
                mWeibo.sendText(content, new TQQApiListener("add_t", false,
                        Main_XuQiu_DetailsActivity.this));
            }
        }
    };
    private AnimationDrawable xuqiu_detail_animation;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                xuqiu_details_PullToRefreshLayout_two.endRefreshing();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        setContentView(R.layout.activity_main__xu_qiu__details);
        /***************初始化*********************/
        init();

        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_xuqiu_details();
            }
        });
        shenqing_duijie.setOnClickListener(this);
        xuqiu_detail_back.setOnClickListener(this);
        xuqiu_details_iamge_collection.setOnClickListener(this);
        tiwen_button.setOnClickListener(this);
        xuqiu_detail_share.setOnClickListener(this);
        xuqiu_details_PullToRefreshLayout_two.setDelegate(this);
        xuqiu_details_PullToRefreshLayout_two.setRefreshViewHolder(new BGANormalRefreshViewHolder(
                getApplicationContext(), true));
    }

    private void init() {
        shenqing_duijie = (Button) findViewById(R.id.shenqing_duijie);
        tiwen_button = (Button) findViewById(R.id.tiwen_button);
        textView_xuqiu_detail_title = (TextView) findViewById(R.id.textView_xuqiu_detail_title);

        xuqiu_details_bianhao = (TextView) findViewById(R.id.xuqiu_details_bianhao);
        xuqiu_fuwu_details_webview = (X5WebView) findViewById(R.id.xuqiu_fuwu_details_webview);
        xuqiu_details_place = (TextView) findViewById(R.id.xuqiu_details_place);
        xuqiu_details_iamge_collection = (ImageView) findViewById(R.id.xuqiu_details_iamge_collection);
        yusuan = (TextView) findViewById(R.id.yusuan);
        fabu = (TextView) findViewById(R.id.fabu);
        // tiwen_number=(TextView) findViewById(R.id.tiwen_number);
        xuqiu_details_PullToRefreshLayout_two = (BGARefreshLayout) findViewById(R.id.xuqiu_details_PullToRefreshLayout_two);
        // xuqiu_mylistview=(MyListview) findViewById(R.id.xuqiu_mylistview);
        xuqiu_detail_load = (ImageView) findViewById(R.id.xuqiu_detail_load);
        xuqiu_detail_animation = (AnimationDrawable) xuqiu_detail_load
                .getDrawable();
        xuqiu_detail_animation.start();

        mTiWen_Adapter = new TiWen_Adapter(this, tiwen_list);

//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        xuqiu_share_url = "http://m.xianjichina.com/require/"
                + getIntent().getStringExtra("xuqiu_id") + ".html";

        xuqiu_detail_back = (RelativeLayout) findViewById(R.id.xuqiu_detail_relative_back);
        xuqiu_detail_share = (ImageView) findViewById(R.id.xuqiu_detail_share);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.shenqing_duijie) {
            if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
                Intent intent = new Intent(Main_XuQiu_DetailsActivity.this,
                        Main_ShengQing_DuiJieActivity.class);
                intent.putExtra("xuqiu_id",
                        getIntent().getStringExtra("xuqiu_id"));

                startActivity(intent);
            } else {
                Toast.makeText(Main_XuQiu_DetailsActivity.this, "请先登录", Toast.LENGTH_SHORT)
                        .show();
                Intent intent = new Intent(Main_XuQiu_DetailsActivity.this,
                        Main_LoginActivity.class);
                intent.putExtra("origin_login", 51);
                startActivity(intent);
            }
        } else if (v.getId() == R.id.xuqiu_detail_relative_back) {
            this.finish();
        } else if (v.getId() == R.id.tiwen_button) {
            if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
                Intent intent = new Intent(Main_XuQiu_DetailsActivity.this,
                        Main_TiWenActivity.class);
                intent.putExtra("xuqiu_id",
                        getIntent().getStringExtra("xuqiu_id"));
                startActivity(intent);
            } else {
                Toast.makeText(Main_XuQiu_DetailsActivity.this, "请先登录", Toast.LENGTH_SHORT)
                        .show();
                Intent intent = new Intent(Main_XuQiu_DetailsActivity.this,
                        Main_LoginActivity.class);
                intent.putExtra("origin_login", 51);
                startActivity(intent);
            }
        } else if (v.getId() == R.id.xuqiu_details_iamge_collection) {
            if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
                collection();
            } else {
                Toast.makeText(Main_XuQiu_DetailsActivity.this, "请先登录", Toast.LENGTH_SHORT)
                        .show();
                startActivity(new Intent(Main_XuQiu_DetailsActivity.this,
                        Main_LoginActivity.class));
            }

        } else if (v.getId() == R.id.xuqiu_detail_share) {
            Photo_show();
            province_gridview.setAdapter(mShare_Adapter);
            show_popupWindow.showAtLocation(findViewById(R.id.xuqiu_detail),
                    Gravity.BOTTOM, 0, 0);
            province_gridview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    if (SharesUtil.getShareList().get(arg2).getName().equals("微信好友")) {
                        SharesUtil.weiXin_showShare(xuqiu_share_url, textView_xuqiu_detail_title.getText().toString());
                    } else if (SharesUtil.getShareList().get(arg2).getName().equals("微信朋友圈")) {
                        SharesUtil.weiXin_prnyyouquan_showShare(xuqiu_share_url, textView_xuqiu_detail_title.getText().toString());
                    } else if (SharesUtil.getShareList().get(arg2).getName().equals("微信收藏")) {
                        SharesUtil.weiXin_collection_showShare(xuqiu_share_url, textView_xuqiu_detail_title.getText().toString());
                    } else if (SharesUtil.getShareList().get(arg2).getName().equals("腾讯微博")) {
                        tengxun_weibo_share();
                    } else if (SharesUtil.getShareList().get(arg2).getName().equals("新浪微博")) {
                        WeiBo_share();
                    } else if (SharesUtil.getShareList().get(arg2).getName().equals("QQ")) {
                        QQ_Share();
                    } else if (SharesUtil.getShareList().get(arg2).getName().equals("QQ空间")) {
                        share_QQ_Qzon();
                    }
                }
            });
        }
    }

    /**
     * 收藏
     */
    public void collection() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("id", id);
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        parms.addBodyParameter("title", textView_xuqiu_detail_title.getText()
                .toString());
        parms.addBodyParameter("type", "demand");
        httpUtils.send(HttpMethod.POST, Contant.collection, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject object = new JSONObject(arg0.result);
                            Toast.makeText(Main_XuQiu_DetailsActivity.this,
                                    object.getString("msg"), Toast.LENGTH_SHORT).show();

                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }
                });
    }

    public void get_xuqiu_details() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("demand_id", getIntent().getStringExtra("xuqiu_id"));
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.xuqiu_details, params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        final JSONObject object = response
                                .getJSONObject("data");
                        Main_XuQiu_DetailsActivity.this.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                xuqiu_detail_animation.stop();
                                xuqiu_detail_load.setVisibility(View.GONE);
                                xuqiu_details_PullToRefreshLayout_two
                                        .setVisibility(View.VISIBLE);
                                try {
                                    textView_xuqiu_detail_title.setText(object
                                            .getString("title"));
                                    if (object.getString("budget").equals(
                                            "negotiable")) {
                                        // negotiable:面议
                                        yusuan.setText("面议");
                                    } else {
                                        // 否则直接获取价格
                                        yusuan.setText(object
                                                .getString("budget_val"));
                                    }
                                    xuqiu_details_bianhao.setText(object
                                            .getString("prono"));
                                    xuqiu_fuwu_details_webview.loadDataWithBaseURL(
                                            null, object.getString("details"),
                                            "text/html", "utf-8", null);
                                    xuqiu_details_place.setText(object
                                            .getString("province_name"));
                                    id = object.getString("id");
                                    if (object.getInt("status") == 1
                                            || object.getInt("status") == 12
                                            || object.getInt("status") == 16
                                            || object.getInt("status") == 17) {
                                        fabu.setText("已发布");
                                    } else if (object.getInt("status") == 11) {
                                        fabu.setText("待审核");
                                    } else if (object.getInt("status") == 10) {
                                        fabu.setText("审核不通过");
                                    } else if (object.getInt("status") == 13
                                            || object.getInt("status") == 14) {
                                        fabu.setText("专家对接中");
                                    } else if (object.getInt("status") == 2) {
                                        fabu.setText("对接中");
                                    } else if (object.getInt("status") == 3
                                            || object.getInt("status") == 31
                                            || object.getInt("status") == 32
                                            || object.getInt("status") == 4
                                            || object.getInt("status") == 41
                                            || object.getInt("status") == 5
                                            || object.getInt("status") == 6) {
                                        fabu.setText("已完结");
                                    } else if (object.getInt("status") == 7
                                            || object.getInt("status") == 71
                                            || object.getInt("status") == 72) {
                                        fabu.setText("结束");
                                    } else if (object.getInt("status") == 8) {
                                        fabu.setText("项目暂停");
                                    }
                                    if (object.getJSONArray("demandqueryok")
                                            .length() > 0) {
                                        tiwen_list.clear();
                                        for (int i = 0; i < object.getJSONArray(
                                                "demandqueryok").length(); i++) {
                                            JSONObject obj = object.getJSONArray(
                                                    "demandqueryok").getJSONObject(
                                                    i);

                                            TiWen mTiWen = new TiWen();
                                            mTiWen.setDetail(obj
                                                    .getString("detail"));
                                            mTiWen.setNickname(obj
                                                    .getString("nickname"));
                                            mTiWen.setQuery(obj.getString("query"));

                                            tiwen_list.add(mTiWen);
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    handler.sendEmptyMessage(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                xuqiu_detail_animation.stop();
                xuqiu_detail_load.setVisibility(View.GONE);
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void Photo_show() {
        layout2 = (LinearLayout) LayoutInflater.from(
                Main_XuQiu_DetailsActivity.this).inflate(
                R.layout.province_popoupwindow_listview, null);
        province_gridview = (GridView) layout2
                .findViewById(R.id.province_gridview);
        if (mShare_Adapter == null) {
            mShare_Adapter = new Share_Adapter(this, SharesUtil.getShareList());
        }
        province_gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        if (show_popupWindow == null) {
            show_popupWindow = new PopupWindow(layout2,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
        }
        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());

        show_popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        show_popupWindow.update();
        show_popupWindow.setOutsideTouchable(true);
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        xuqiu_fuwu_details_webview = null;
    }

    /**
     * QQ
     *
     * @return
     */
    public void QQ_Share() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
                QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "贤集网");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY,
                textView_xuqiu_detail_title.getText().toString());
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, xuqiu_share_url);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "贤集网");
        XJApplication.getTencent().shareToQQ(Main_XuQiu_DetailsActivity.this,
                params, new Share_Listener());
    }

    public void share_QQ_Qzon() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,
                QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "贤集网");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY,
                textView_xuqiu_detail_title.getText().toString());
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, xuqiu_share_url);

        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "贤集网");

        XJApplication.getTencent().shareToQQ(Main_XuQiu_DetailsActivity.this,
                params, new Share_Listener());
    }

    private void tengxun_weibo_share() {
        XJApplication.getTencent().login(Main_XuQiu_DetailsActivity.this,
                "all", loginListener);
    }

    /**
     * 腾讯微博
     */
    public void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                XJApplication.getTencent().setAccessToken(token, expires);
                XJApplication.getTencent().setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 腾讯微博是否登录
     *
     * @param context
     * @return
     */
    public boolean ready(Context context) {
        if (XJApplication.getTencent() == null) {
            return false;
        }
        boolean ready = XJApplication.getTencent().isSessionValid()
                && XJApplication.getTencent().getQQToken().getOpenId() != null;
        if (!ready) {
            Toast.makeText(context, "login and get openId first, please!",
                    Toast.LENGTH_SHORT).show();
        }
        return ready;
    }

    private void WeiBo_share() {
        mSsoHandler = new SsoHandler(Main_XuQiu_DetailsActivity.this,
                XJApplication.mAuthInfo);

        mSsoHandler.authorizeClientSso(new AuthListener());

        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(
                Main_XuQiu_DetailsActivity.this, "4216978203");

        mWeiboShareAPI.registerApp();

        isInstalledWeibo = mWeiboShareAPI.isWeiboAppInstalled();

        supportApiLevel = mWeiboShareAPI.getWeiboAppSupportAPI();

        mWeiboShareAPI.handleWeiboResponse(getIntent(),
                Main_XuQiu_DetailsActivity.this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResp) {
        if (baseResp != null) {
            switch (baseResp.errCode) {
                case WBConstants.ErrorCode.ERR_OK:
                    Toast.makeText(this, "成功", Toast.LENGTH_LONG).show();
                    break;
                case WBConstants.ErrorCode.ERR_CANCEL:
                    Toast.makeText(this, "取消", Toast.LENGTH_LONG).show();
                    break;
                case WBConstants.ErrorCode.ERR_FAIL:
                    Toast.makeText(this, "Error Message: " + baseResp.errMsg,
                            Toast.LENGTH_LONG).show();
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // SSO 授权回调
        // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResults
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }

        if (requestCode == Constants.REQUEST_LOGIN
                || requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data,
                    loginListener);
        }
        /****************************** QQ 分享 必须加的，回调不起作用 ********************************/
        // 官方文档没这句代码, 但是很很很重要, 不然不会回调!
        Tencent.onActivityResultData(requestCode, resultCode, data,
                new Share_Listener());

        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE
                    || resultCode == Constants.REQUEST_QZONE_SHARE
                    || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, new Share_Listener());
            }
        }
    }

    private BaseMediaObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = textView_xuqiu_detail_title.getText().toString();
        mediaObject.description = "贤集网" + xuqiu_share_url;

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.touxiang);
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = xuqiu_share_url;
        mediaObject.defaultText = "";
        return mediaObject;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        get_xuqiu_details();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(
            BGARefreshLayout refreshLayout) {
        return true;
    }

    public class Share_Listener implements IUiListener {
        @Override
        public void onCancel() {
            Toast.makeText(Main_XuQiu_DetailsActivity.this, "取消", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onComplete(Object arg0) {
            Toast.makeText(Main_XuQiu_DetailsActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(UiError arg0) {
            Toast.makeText(Main_XuQiu_DetailsActivity.this, arg0 + "", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 腾讯微博
     */
    private class BaseUiListener implements IUiListener {
        @Override
        public void onComplete(Object response) {
            if (null == response) {
                Toast.makeText(Main_XuQiu_DetailsActivity.this, "登录失败", Toast.LENGTH_SHORT)
                        .show();
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                Toast.makeText(Main_XuQiu_DetailsActivity.this, "登录失败", Toast.LENGTH_SHORT)
                        .show();
                return;
            }
            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {
        }

        @Override
        public void onError(UiError e) {
            Toast.makeText(Main_XuQiu_DetailsActivity.this, e.errorDetail, Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(Main_XuQiu_DetailsActivity.this, "oncancle", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    /**
     * 腾讯微博
     *
     * @author me
     */
    private class TQQApiListener extends BaseUiListener {
        private String mScope = "all";
        private Boolean mNeedReAuth = false;
        private Activity mActivity;

        public TQQApiListener(String mScope, Boolean mNeedReAuth,
                              Activity mActivity) {
            super();
            this.mScope = mScope;
            this.mNeedReAuth = mNeedReAuth;
            this.mActivity = mActivity;
        }

        @Override
        public void onComplete(Object response) {
            final Activity activity = Main_XuQiu_DetailsActivity.this;
            try {
                JSONObject json = (JSONObject) response;
                int ret = json.getInt("ret");
                if (ret == 0) {
                    Toast.makeText(Main_XuQiu_DetailsActivity.this, "微博发送成功", Toast.LENGTH_SHORT)
                            .show();
                } else if (ret == 100030) {
                    if (mNeedReAuth) {
                        Runnable r = new Runnable() {
                            public void run() {
                                XJApplication.getTencent().reAuth(activity,
                                        mScope, new BaseUiListener());
                            }
                        };
                        Main_XuQiu_DetailsActivity.this.runOnUiThread(r);
                    }
                } else if (ret == 6) {
                    Toast.makeText(Main_XuQiu_DetailsActivity.this, "该账号未开通微博",
                            Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    class AuthListener implements WeiboAuthListener {
        @Override
        public void onComplete(Bundle values) {
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            String phoneNum = mAccessToken.getPhoneNum();
            if (mAccessToken.isSessionValid()) {
                if (isInstalledWeibo) {
                    if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
                        if (supportApiLevel >= 10351 /*
                         * ApiUtils.BUILD_INT_VER_2_2
                         */) {
                            WeiboMultiMessage weiboMessage = new WeiboMultiMessage();

                            weiboMessage.mediaObject = getWebpageObj();
                            SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
                            request.transaction = String.valueOf(System
                                    .currentTimeMillis());
                            request.multiMessage = weiboMessage;
                            mWeiboShareAPI.sendRequest(
                                    Main_XuQiu_DetailsActivity.this, request);
                        } else {
                            WeiboMessage weiboMessage = new WeiboMessage();
                            weiboMessage.mediaObject = getWebpageObj();
                            SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
                            request.transaction = String.valueOf(System
                                    .currentTimeMillis());
                            request.message = weiboMessage;
                            mWeiboShareAPI.sendRequest(
                                    Main_XuQiu_DetailsActivity.this, request);
                        }
                    }
                }
                Toast.makeText(Main_XuQiu_DetailsActivity.this, "授权成功",
                        Toast.LENGTH_SHORT).show();
            } else {
                String code = values.getString("code");
                Toast.makeText(Main_XuQiu_DetailsActivity.this, "授权失败",
                        Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(Main_XuQiu_DetailsActivity.this, "取消",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(Main_XuQiu_DetailsActivity.this,
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
    }
}